<?php

namespace app\controller\adminapi\user;

use app\common\model\addon\Addons;
use app\common\model\attachment\Attachment;
use app\common\model\attachment\AttachmentGroup;
use app\common\model\platform\Platform;
use app\common\model\user\UserGroup;
use app\common\model\user\User as UserModel;
use app\common\model\user\UserToken;
use app\common\model\user\UserWallet;
use app\common\services\table\Column;
use app\common\services\table\DataForm;
use app\common\services\table\DataTable;
use hiduoke\controller\AdminController;
use hiduoke\services\FormBuilder as Form;
use app\common\model\addonAuth\AddonGroup;
use hiduoke\services\Random;

/**
 * Notes: 用户管理
 * Create by :  刘泓宾<514660094@qq.com>
 * Copyright :  copyright (c) 多客怪兽, www.dkyx.cc
 * Created on:  2025/8/6 03:50
 */
class User extends AdminController
{
    protected $notLogin = ['login'];
    protected array $withJoinTable = ['userGroup', 'addonGroup'];


    /**
     * @var UserModel
     */
    public $UserModel = null;

    public function initialize()
    {
        $this->UserModel = new UserModel();
        $this->model = new UserModel();
    }

    // 新版本用户列表
    public function table()
    {
        $DataTable = (new DataTable($this->model));
        if ($this->request->param('recycle')) {
            // 回收站
            $DataTable->field([$this->model->getPk(), 'delete_time']);
        }
        $button = Column::make()->demoButton;
        $button['type'] = 'warning';
        // 按钮的属性参数
        $button['attr'] = [];
        $addonButton = array_merge($button, ['title' => '扩展', "text" => "扩展", 'icon' => 'Grid', 'name' => 'setting', 'type' => 'primary']);
        $platformButton = array_merge($button, ['title' => '平台', "text" => "平台", 'icon' => 'Grid', 'name' => 'platform', 'type' => 'primary']);
        $column = $DataTable
            ->setFilterFields(['token', 'password', 'salt', 'is_admin','addons_auth'])
            ->setHideFields(['update_time', 'create_time', 'join_ip', 'login_ip', 'join_ip', 'login_fail', 'prev_time', 'login_time'])
            ->setAfterField('status',
                Column::make()
                    ->label('可创建平台数')
                    ->width('220px')
                    ->prop('platform')
                    ->slotName('platform_slot')
                    ->render('slot')
                    ->create())
            // 设置 站点ID (site_id) 字段自定义配置
            ->setField("group_id", [
                "label"         => "管理组",
                "prop"          => "userGroup.group_name",
                "comSearchProp" => "group_id",
                "type"          => "remoteSelect",
                "render"        => "slot",
                "slotName"      => "group_slot",
                'remoteUrl'     => '/adminapi/user.group?label=group_name&val=id'
            ])
            ->setField('addon_group_id', [
                "label"     => "应用组", "prop" => "addonGroup.name", "comSearchProp" => "addon_group_id", "type" => "remoteSelect",
                "render"    => "slot",
                "slotName"  => "addon_group_slot",
                'remoteUrl' => '/adminapi/addonGroup/index?label=name&val=id'
            ])
            ->setField('is_admin', ['label' => '管理员'])
            ->setField('login_time', ['render' => 'datetime'])
            ->setField('prev_time', ['render' => 'datetime'])
            ->setField('avatar', ['align' => 'center'])
            ->setField('status', ['custom' => ['-1' => 'danger', '0' => 'success']])
            ->operation(
                Column::make()->prop('operation')
                    // 操作列标题
                    ->label('操作')
                    ->render('buttons')
                    // 宽度
                    ->width(150)
                    ->other('fixed', 'right')
                    // 禁用搜索
                    ->operator(false)
                    // 自定义按钮组
                    ->buttons([
                        $addonButton,
                        $platformButton,
                        "edit", "del"
                    ])
                    ->create()
            )->create();
        return $this->success('ok', ['column' => $column, 'pk' => $this->model->getPk()]);
    }


    public function index()
    {
        if ($this->request->param('select')) {
            return $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->append(['wallet'])
            ->paginate($limit);
        return $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ], $this->model->getLastSql());
    }

    /**
     * 获取表单
     * @param $id
     * @return \think\response\Json
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function form()
    {
        $dataForm = new DataForm($this->model);
        $rule = array();
        //创建表单
        $form = Form::createForm("/adminapi/user/setUserForm")->setMethod("POST");
        $user_group_options = UserGroup::getUserGroupOption();
        $addon_group_options = AddonGroup::getAddonGroupOption();
        $user = $dataForm->row;
        if (!$user->isEmpty()) {
            $title = "编辑用户";
            $rule[] = Form::input('uid', '用户ID', $user->uid ?? 0)->disabled(true);
            $rule[] = Form::input('username', '登录账号', $user->username ?? '')->disabled(true);
            $rule[] = Form::input('password', '修改密码', '')->placeholder("修改密码，不填则密码不改变");
        } else {
            $title = "新增用户";
            $rule[] = Form::input('username', '登录账号', "")->required();
            $rule[] = Form::input('password', '登录密码', "")->required();
        }
        $rule[] = Form::dkImage('avatar', '头像', $user->avatar ?? '')->appendToBody();
        $rule[] = Form::radio('is_admin', '管理员', $user->is_admin ?? 0)
            ->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->appendControl(1, [
                Form::select("group_id", "管理用户组", $user->group_id ?? 0)->options($user_group_options)->filterable(true)
            ]);
        $rule[] = Form::select("addon_group_id", "应用组", $user->addon_group_id ?? 0)->options($addon_group_options)->filterable(true);
        $Addons = new Addons();
        $addonsExplain = $Addons->getAddonsByFormDataAddons($user->addons_auth ?? []);
        $rule[] = Form::dkAddonSelect("addons_auth", "扩展应用", $user->addons_auth ?? [])
            ->addonsExplain($addonsExplain)
            ->appendToBody()
            ->effect(['help' => '为当前用户添加额外的应用权限']);
        $rule[] = Form::radio('status', '状态', intval($user->status ?? 0))
            ->options([['label' => '正常', 'value' => 0], ['label' => '禁用', 'value' => -1]]);
        $rule[] = Form::input('phone', '电话', $user->phone ?? '');
        $rule[] = Form::input('remark', '备注', $user->remark ?? '');
        $form->setTitle($title)->setRule($rule)->setConfig(['dialog'=>['top'=>'5vh']]);
        return $this->success('', Form::getFormData($form));
    }

    // end  新版本用户列表

    /**
     * 用户登录
     */
    public function login()
    {
        $username = input("username", '');
        $password = input("password", '');
        if ($this->auth->login($username, $password) && !$this->auth->getError()) {
            $userinfo = $this->auth->getUserinfo();
            $userinfo['token'] = $this->auth->getToken();
            return $this->success("ok", $userinfo);
        } else {
            return $this->error($this->auth->getError());
        }
    }

    /**
     * 获取用户信息
     * @return \think\response\Json
     */
    public function info()
    {
        return $this->success('ok', $this->userInfo);
    }

    /**
     * 退出登录
     * @return \think\response\Json
     */
    public function logout()
    {
        $this->auth->logout();
        return $this->success('logout_success');
    }

//    //获取用户列表
//    public function getList()
//    {
//        $data = $this->UserModel->getPageListData()->append(['group_name', 'wallet', 'addon_group_name']);
//        $count = $this->UserModel->getPageListCount();
//        return $this->success($count, $data);
//    }

//    /**
//     * TODO old 获取用户编辑表单
//     * @return \think\response\Json
//     * @throws \FormBuilder\Exception\FormBuilderException
//     * @throws \think\db\exception\DataNotFoundException
//     * @throws \think\db\exception\DbException
//     * @throws \think\db\exception\ModelNotFoundException
//     */
//    public function getUserForm()
//    {
//        $uid = input('uid');
//        $rule = array();
//        //创建表单
//        $form = Form::createForm("/adminapi/user/setUserForm")->setMethod("POST");
//        $user_group_options = UserGroup::getUserGroupOption();
//        $addon_group_options = AddonGroup::getAddonGroupOption();
//        $user = $this->UserModel::withSearch(['uid'], ['uid' => $uid])->append(['wallet'])->findOrEmpty();
//        if (!$user->isEmpty()) {
//            $title = "编辑用户";
//            $rule[] = Form::input('uid', '用户ID', $user->uid ?? 0)->disabled(true);
//            $rule[] = Form::input('username', '登录账号', $user->username ?? '')->disabled(true);
//            $rule[] = Form::input('password', '修改密码', '')->placeholder("修改密码，不填则密码不改变");
//        } else {
//            $title = "新增用户";
//            $rule[] = Form::input('username', '登录账号', "")->required();
//            $rule[] = Form::input('password', '登录密码', "")->required();
//        }
//
//        $rule[] = Form::dkImage('avatar', '头像', $user->avatar ?? '')->appendToBody();
//        $rule[] = Form::radio('is_admin', '是否为管理员', $user->is_admin ?? 0)
//            ->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->appendControl(1, [
//                Form::select("group_id", "管理用户组", $user->group_id ?? 0)->options($user_group_options)->filterable(true)
//            ]);
//        $rule[] = Form::select("addon_group_id", "应用组", $user->addon_group_id ?? 0)->options($addon_group_options)->filterable(true);
//        $rule[] = Form::radio('status', '状态', $user->status ?? 0)->options([['label' => '正常', 'value' => 0], ['label' => '禁用', 'value' => -1]]);
//        $rule[] = Form::input('phone', '电话', $user->phone ?? '');
//        $rule[] = Form::input('remark', '备注', $user->remark ?? '');
//        $form->setTitle($title)->setRule($rule);
//        return $this->success('', Form::getFormData($form));
//    }

    /**
     * 编辑和新增用户
     * @return \think\response\Json
     */
    public function setUserForm()
    {
        $formData = input('formData', []);
        $uid = isset($formData["uid"]) ? $formData["uid"] : 0;
        $user = $this->UserModel::withSearch(['uid'], ['uid' => $uid])->findOrEmpty();
        if ($user->isEmpty()) {
            //不存在为新增
            $msg = '新增成功';
            if ($this->UserModel::checkUnique(['username' => $formData['username']])) {
                return $this->error("用户名已存在");
            }
            $formData['salt'] = Random::alnum();
            $formData['password'] = $this->auth->getEncryptPassword($formData['password'], $formData['salt']);
        } else {
            $msg = '修改成功';
            if ($formData['password']) {
                $this->auth->changePwdByUid($formData['uid'], $formData['password']);
            }
            unset($formData['password']);
        }
        $user->save($formData);
        return $this->success($msg);
    }

    /**
     * 删除用户
     */
    public function deleteUser()
    {
        $uid = input("uid", 0);
        $this->UserModel->where(['uid' => $uid])->delete();
        // TODO 删除用户事件,这个后期看需不需要写到auth里面
        event("user_delete_success", $uid);
        return $this->success("删除成功");
    }

    public function getUserWalletForm()
    {
        $uid = input('uid');
        $rule = array();
        //创建表单
        $form = Form::createForm("/adminapi/user/setUserWalletForm")->setMethod("POST");
        $wallet = UserWallet::where(['uid' => $uid])->findOrEmpty();
        $title = "编辑用户资产";
        $rule[] = Form::hidden('uid', $wallet->uid ?? $uid);
        $rule[] = Form::number('wechat', '微信公众平台', $wallet->wechat ?? 0);
        $rule[] = Form::number('free', '自由平台', $wallet->free ?? 0);
        $rule[] = Form::number('douyin', '抖音', $wallet->douyin ?? 0);
        $rule[] = Form::number('work_wechat', '企业微信', $wallet->work_wechat ?? 0);
        $rule[] = Form::number('min_app', '小程序集', $wallet->min_app ?? 0);
        $form->setTitle($title)->setRule($rule);
        return $this->success('', Form::getFormData($form));
    }

    public function setUserWalletForm()
    {
        $formData = input('formData', []);
        $uid = isset($formData["uid"]) ? $formData["uid"] : 0;
        $wallet = UserWallet::where(['uid' => $uid])->findOrEmpty();
        $wallet->save($formData);
        return $this->success("修改成功");
    }

    /**
     * 删除用户
     */
    public function delete()
    {
        $uid = input('uid', 0);
        (new \app\common\model\user\UserPermission())->where(['uid' => $uid])->delete();
        (new UserToken())->where(['uid' => $uid])->delete();
        (new UserWallet())->where(['uid' => $uid])->delete();
        (new Attachment())->where(['uid' => $uid])->delete();
        (new AttachmentGroup())->where(['uid' => $uid])->delete();
        (new Platform())->where(['uid' => $uid])->delete();
        $this->UserModel->where(['uid' => $uid])->delete();
        return $this->success("删除成功");
        // 删除用户 user
        // 删除应用 user_addon
        // 删除用户应用组 user_addon_group
        // 删除用户权限 user_permission
        // 用户附件 attachment
        // 用户附件组 attachment_group
        // 平台 platform
        // Token user_token
        // 删除用户钱包 user_wallet
    }
}
